/*
 * @Author: Liz.Zheng
 * @Date: 2021-09-24 16:23:18
 * @LastEditTime: 2022-07-15 17:34:11
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description:
 * @Motto: Write the code. Change the world.
 */
import { createApp } from "vue";
import App from "./App.vue";
import appUse from "./common/utils/app_use";
import actions from "./common/utils/action";
import store from "./store";
import utils from "./common/utils/utils";
import router from "./router";
import "./common/styles/common.less";
import "./common/utils/permission";
import "./common/styles/global.css";
import defaultSetting from "./common/utils/defaultSetting";
import moment from "moment";
import duration from 'dayjs/plugin/duration';
import components from "./router/components";
moment.extend(duration);

let app = null;

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  let loaded = false;
  import(`ant-design-vue/dist/antd.less`).then((data) => {
    if (window.self !== window.top) {
      // 判断链接带token或者本地有token直接渲染
      let token =
        utils.getStorage(`token`) ||
        localStorage.getItem(`${defaultSetting.from}_orgMain_org_token`) ||
        localStorage.getItem(`${defaultSetting.from}_systemMain_token`);
      if (token) {
        store.dispatch("SetToken", token);
      }
      const currentParams = location.href.split("?")[1];
      if (token || (currentParams && currentParams.indexOf("token") > -1)) {
        if (!loaded) {
          render();
          loaded = true;
        }
      }
    }
  });
  if (window.self !== window.top) {
    // 如果是iframe需要接收父窗口传来的信息
    window.onmessage = (e) => {
      if (e.data) {
        console.log("onmessage", e.data.type);
        if (e.data.type == "mainRefresh") {
          location.reload();
        }
        if (e.data.type == "mainMessage") {
          store.dispatch("SetIframeData", e.data).then(() => {
            if (!loaded) {
              render();
              loaded = true;
            }
          });
        }
        if (e.data.type == "back") {
          router.back();
        }
        if (e.data.type == "forward") {
          router.forward();
        }
      }
    };
  } else {
    render();
  }
}

function render(props = {}) {
  if (window.__POWERED_BY_QIANKUN__) {
    saveProps(props);
  }

  const { container } = props;
  const root = container ? container.querySelector("#app") : "#app";

  app = createApp(App);
  appUse(app);
  app.mount(root);
  renderPatch(props);
}

function saveProps(props = {}) {
  if (Object.keys(props).length) {
    window.ORGCOMMON_BASE_URL = props.customDomain;
    store.dispatch("SetMainAppProps", props).then((res) => {
      const { tokenName, sessionName } = res;
      // 取出token到vuex
      if (tokenName) {
        const token = localStorage.getItem(tokenName);
        if (token) {
          store.dispatch("SetToken", token);
        }
        if (sessionName) {
          store.dispatch("SetSession", sessionName);
        }
      }
    });
  }
}

function renderPatch(props) {
  const { currentPathName, currentParams, appHeight, containerPage,
    component, } = props;
  if (containerPage && component) {
    router.addRoute("main", {
      path: containerPage,
      name: currentPathName,
      component: components[component], // 建议与currentPathName一致
    });
    utils.setStorage("approval_id", JSON.stringify(currentParams));
    router.push({ name: currentPathName, params: currentParams }); // params传参仅支持vue-router4.1.4以下版本，如果页面内取不到此参数，建议存储vuex再取
  } else if (currentPathName) {
    // 跳转路由
    router.push({ name: currentPathName, query: currentParams });
  }
  if (appHeight) {
    store.dispatch("SetAppHeight", appHeight);
  }
}

export async function bootstrap() {
  utils.consoleInfo("bootstraped");
}
export async function mount(props) {
  utils.consoleInfo("mounted");
  // 初始化actions
  actions.setActions(props);
  // 监听数据变化
  actions.onGlobalStateChange((state, preState) => {
    if (state.appHeight && state.appHeight != preState.appHeight) {
      store.dispatch("SetAppHeight", state.appHeight);
    }
  });
  render(props);
}

export async function update(props) {
  utils.consoleInfo(props, "update");
  renderPatch(props);
}

export async function unmount() {
  utils.consoleInfo(app, "unmount");
  app.unmount();
}
